﻿
using System;
using System.Data;
using System.Text;
using System.Data.SqlClient;
using jutehui.IDAL;
using Maticsoft.DBUtility;//Please add references
namespace jutehui.SQLServerDAL
{
	/// <summary>
	/// 数据访问类:secondKillProducts
	/// </summary>
	public partial class secondKillProducts:IsecondKillProducts
	{
		public secondKillProducts()
		{}
		#region  BasicMethod

		/// <summary>
		/// 是否存在该记录
		/// </summary>
		public bool Exists(long PId)
		{
			StringBuilder strSql=new StringBuilder();
			strSql.Append("select count(1) from secondKillProducts");
			strSql.Append(" where PId=@PId");
			SqlParameter[] parameters = {
					new SqlParameter("@PId", SqlDbType.BigInt)
			};
			parameters[0].Value = PId;

			return DbHelperSQL.Exists(strSql.ToString(),parameters);
		}


		/// <summary>
		/// 增加一条数据
		/// </summary>
		public long Add(jutehui.Model.secondKillProducts model)
		{
			StringBuilder strSql=new StringBuilder();
			strSql.Append("insert into secondKillProducts(");
			strSql.Append("ProducerId,Pname,Plink,CurrentPrice,OldPrice,ImgUrl,SoldState,Source,UpdateTime,Memo,ProductTypeId,TypeId,PriceType,UpdateTimeStr,DeleteTime,Down,InTimeQuantum)");
			strSql.Append(" values (");
			strSql.Append("@ProducerId,@Pname,@Plink,@CurrentPrice,@OldPrice,@ImgUrl,@SoldState,@Source,@UpdateTime,@Memo,@ProductTypeId,@TypeId,@PriceType,@UpdateTimeStr,@DeleteTime,@Down,@InTimeQuantum)");
			strSql.Append(";select @@IDENTITY");
			SqlParameter[] parameters = {
					new SqlParameter("@ProducerId", SqlDbType.Int,4),
					new SqlParameter("@Pname", SqlDbType.VarChar,-1),
					new SqlParameter("@Plink", SqlDbType.VarChar,-1),
					new SqlParameter("@CurrentPrice", SqlDbType.VarChar,50),
					new SqlParameter("@OldPrice", SqlDbType.VarChar,50),
					new SqlParameter("@ImgUrl", SqlDbType.VarChar,-1),
					new SqlParameter("@SoldState", SqlDbType.VarChar,50),
					new SqlParameter("@Source", SqlDbType.VarChar,150),
					new SqlParameter("@UpdateTime", SqlDbType.DateTime),
					new SqlParameter("@Memo", SqlDbType.VarChar,-1),
					new SqlParameter("@ProductTypeId", SqlDbType.BigInt,8),
					new SqlParameter("@TypeId", SqlDbType.BigInt,8),
					new SqlParameter("@PriceType", SqlDbType.NVarChar,10),
					new SqlParameter("@UpdateTimeStr", SqlDbType.VarChar,50),
					new SqlParameter("@DeleteTime", SqlDbType.DateTime),
					new SqlParameter("@Down", SqlDbType.Int,4),
					new SqlParameter("@InTimeQuantum", SqlDbType.Int,4)};
			parameters[0].Value = model.ProducerId;
			parameters[1].Value = model.Pname;
			parameters[2].Value = model.Plink;
			parameters[3].Value = model.CurrentPrice;
			parameters[4].Value = model.OldPrice;
			parameters[5].Value = model.ImgUrl;
			parameters[6].Value = model.SoldState;
			parameters[7].Value = model.Source;
			parameters[8].Value = model.UpdateTime;
			parameters[9].Value = model.Memo;
			parameters[10].Value = model.ProductTypeId;
			parameters[11].Value = model.TypeId;
			parameters[12].Value = model.PriceType;
			parameters[13].Value = model.UpdateTimeStr;
			parameters[14].Value = model.DeleteTime;
			parameters[15].Value = model.Down;
			parameters[16].Value = model.InTimeQuantum;

			object obj = DbHelperSQL.GetSingle(strSql.ToString(),parameters);
			if (obj == null)
			{
				return 0;
			}
			else
			{
				return Convert.ToInt64(obj);
			}
		}
		/// <summary>
		/// 更新一条数据
		/// </summary>
		public bool Update(jutehui.Model.secondKillProducts model)
		{
			StringBuilder strSql=new StringBuilder();
			strSql.Append("update secondKillProducts set ");
			strSql.Append("ProducerId=@ProducerId,");
			strSql.Append("Pname=@Pname,");
			strSql.Append("Plink=@Plink,");
			strSql.Append("CurrentPrice=@CurrentPrice,");
			strSql.Append("OldPrice=@OldPrice,");
			strSql.Append("ImgUrl=@ImgUrl,");
			strSql.Append("SoldState=@SoldState,");
			strSql.Append("Source=@Source,");
			strSql.Append("UpdateTime=@UpdateTime,");
			strSql.Append("Memo=@Memo,");
			strSql.Append("ProductTypeId=@ProductTypeId,");
			strSql.Append("TypeId=@TypeId,");
			strSql.Append("PriceType=@PriceType,");
			strSql.Append("UpdateTimeStr=@UpdateTimeStr,");
			strSql.Append("DeleteTime=@DeleteTime,");
			strSql.Append("Down=@Down,");
			strSql.Append("InTimeQuantum=@InTimeQuantum");
			strSql.Append(" where PId=@PId");
			SqlParameter[] parameters = {
					new SqlParameter("@ProducerId", SqlDbType.Int,4),
					new SqlParameter("@Pname", SqlDbType.VarChar,-1),
					new SqlParameter("@Plink", SqlDbType.VarChar,-1),
					new SqlParameter("@CurrentPrice", SqlDbType.VarChar,50),
					new SqlParameter("@OldPrice", SqlDbType.VarChar,50),
					new SqlParameter("@ImgUrl", SqlDbType.VarChar,-1),
					new SqlParameter("@SoldState", SqlDbType.VarChar,50),
					new SqlParameter("@Source", SqlDbType.VarChar,150),
					new SqlParameter("@UpdateTime", SqlDbType.DateTime),
					new SqlParameter("@Memo", SqlDbType.VarChar,-1),
					new SqlParameter("@ProductTypeId", SqlDbType.BigInt,8),
					new SqlParameter("@TypeId", SqlDbType.BigInt,8),
					new SqlParameter("@PriceType", SqlDbType.NVarChar,10),
					new SqlParameter("@UpdateTimeStr", SqlDbType.VarChar,50),
					new SqlParameter("@DeleteTime", SqlDbType.DateTime),
					new SqlParameter("@Down", SqlDbType.Int,4),
					new SqlParameter("@InTimeQuantum", SqlDbType.Int,4),
					new SqlParameter("@PId", SqlDbType.BigInt,8)};
			parameters[0].Value = model.ProducerId;
			parameters[1].Value = model.Pname;
			parameters[2].Value = model.Plink;
			parameters[3].Value = model.CurrentPrice;
			parameters[4].Value = model.OldPrice;
			parameters[5].Value = model.ImgUrl;
			parameters[6].Value = model.SoldState;
			parameters[7].Value = model.Source;
			parameters[8].Value = model.UpdateTime;
			parameters[9].Value = model.Memo;
			parameters[10].Value = model.ProductTypeId;
			parameters[11].Value = model.TypeId;
			parameters[12].Value = model.PriceType;
			parameters[13].Value = model.UpdateTimeStr;
			parameters[14].Value = model.DeleteTime;
			parameters[15].Value = model.Down;
			parameters[16].Value = model.InTimeQuantum;
			parameters[17].Value = model.PId;

			int rows=DbHelperSQL.ExecuteSql(strSql.ToString(),parameters);
			if (rows > 0)
			{
				return true;
			}
			else
			{
				return false;
			}
		}

		/// <summary>
		/// 删除一条数据
		/// </summary>
		public bool Delete(DateTime dateTime)
		{
			
			StringBuilder strSql=new StringBuilder();
			strSql.Append("delete from secondKillProducts ");
            strSql.Append(" where UpdateTime<@UpdateTime");
			SqlParameter[] parameters = {
					new SqlParameter("@UpdateTime", SqlDbType.DateTime)
			};
            parameters[0].Value = dateTime;

			int rows=DbHelperSQL.ExecuteSql(strSql.ToString(),parameters);
			if (rows > 0)
			{
				return true;
			}
			else
			{
				return false;
			}
		}
		/// <summary>
		/// 批量删除数据
		/// </summary>
		public bool DeleteList(string PIdlist )
		{
			StringBuilder strSql=new StringBuilder();
			strSql.Append("delete from secondKillProducts ");
			strSql.Append(" where PId in ("+PIdlist + ")  ");
			int rows=DbHelperSQL.ExecuteSql(strSql.ToString());
			if (rows > 0)
			{
				return true;
			}
			else
			{
				return false;
			}
		}


		/// <summary>
		/// 得到一个对象实体
		/// </summary>
		public jutehui.Model.secondKillProducts GetModel(long PId)
		{
			
			StringBuilder strSql=new StringBuilder();
			strSql.Append("select  top 1 PId,ProducerId,Pname,Plink,CurrentPrice,OldPrice,ImgUrl,SoldState,Source,UpdateTime,Memo,ProductTypeId,TypeId,PriceType,UpdateTimeStr,DeleteTime,Down,InTimeQuantum from secondKillProducts ");
			strSql.Append(" where PId=@PId");
			SqlParameter[] parameters = {
					new SqlParameter("@PId", SqlDbType.BigInt)
			};
			parameters[0].Value = PId;

			jutehui.Model.secondKillProducts model=new jutehui.Model.secondKillProducts();
			DataSet ds=DbHelperSQL.Query(strSql.ToString(),parameters);
			if(ds.Tables[0].Rows.Count>0)
			{
				return DataRowToModel(ds.Tables[0].Rows[0]);
			}
			else
			{
				return null;
			}
		}


		/// <summary>
		/// 得到一个对象实体
		/// </summary>
		public jutehui.Model.secondKillProducts DataRowToModel(DataRow row)
		{
            jutehui.Model.secondKillProducts model = new jutehui.Model.secondKillProducts();
			if (row != null)
			{
				if(row["PId"]!=null && row["PId"].ToString()!="")
				{
					model.PId=long.Parse(row["PId"].ToString());
				}
				if(row["ProducerId"]!=null && row["ProducerId"].ToString()!="")
				{
					model.ProducerId=int.Parse(row["ProducerId"].ToString());
				}
				if(row["Pname"]!=null)
				{
					model.Pname=row["Pname"].ToString();
				}
				if(row["Plink"]!=null)
				{
					model.Plink=row["Plink"].ToString();
				}
				if(row["CurrentPrice"]!=null)
				{
					model.CurrentPrice=row["CurrentPrice"].ToString();
				}
				if(row["OldPrice"]!=null)
				{
					model.OldPrice=row["OldPrice"].ToString();
				}
				if(row["ImgUrl"]!=null)
				{
					model.ImgUrl=row["ImgUrl"].ToString();
				}
				if(row["SoldState"]!=null)
				{
					model.SoldState=row["SoldState"].ToString();
				}
				if(row["Source"]!=null)
				{
					model.Source=row["Source"].ToString();
				}
				if(row["UpdateTime"]!=null && row["UpdateTime"].ToString()!="")
				{
					model.UpdateTime=DateTime.Parse(row["UpdateTime"].ToString());
				}
				if(row["Memo"]!=null)
				{
					model.Memo=row["Memo"].ToString();
				}
				if(row["ProductTypeId"]!=null && row["ProductTypeId"].ToString()!="")
				{
					model.ProductTypeId=long.Parse(row["ProductTypeId"].ToString());
				}
				if(row["TypeId"]!=null && row["TypeId"].ToString()!="")
				{
					model.TypeId=long.Parse(row["TypeId"].ToString());
				}
				if(row["PriceType"]!=null)
				{
					model.PriceType=row["PriceType"].ToString();
				}
				if(row["UpdateTimeStr"]!=null)
				{
					model.UpdateTimeStr=row["UpdateTimeStr"].ToString();
				}
				if(row["DeleteTime"]!=null && row["DeleteTime"].ToString()!="")
				{
					model.DeleteTime=DateTime.Parse(row["DeleteTime"].ToString());
				}
				if(row["Down"]!=null && row["Down"].ToString()!="")
				{
					model.Down=int.Parse(row["Down"].ToString());
				}
				if(row["InTimeQuantum"]!=null && row["InTimeQuantum"].ToString()!="")
				{
					model.InTimeQuantum=int.Parse(row["InTimeQuantum"].ToString());
				}
			}
			return model;
		}

		/// <summary>
		/// 获得数据列表
		/// </summary>
		public DataSet GetList(string strWhere)
		{
			StringBuilder strSql=new StringBuilder();
			strSql.Append("select PId,ProducerId,Pname,Plink,CurrentPrice,OldPrice,ImgUrl,SoldState,Source,UpdateTime,Memo,ProductTypeId,TypeId,PriceType,UpdateTimeStr,DeleteTime,Down,InTimeQuantum ");
			strSql.Append(" FROM secondKillProducts ");
			if(strWhere.Trim()!="")
			{
				strSql.Append(" where "+strWhere);
			}
			return DbHelperSQL.Query(strSql.ToString());
		}

		/// <summary>
		/// 获得前几行数据
		/// </summary>
		public DataSet GetList(int Top,string strWhere,string filedOrder)
		{
			StringBuilder strSql=new StringBuilder();
			strSql.Append("select ");
			if(Top>0)
			{
				strSql.Append(" top "+Top.ToString());
			}
			strSql.Append(" PId,ProducerId,Pname,Plink,CurrentPrice,OldPrice,ImgUrl,SoldState,Source,UpdateTime,Memo,ProductTypeId,TypeId,PriceType,UpdateTimeStr,DeleteTime,Down,InTimeQuantum ");
			strSql.Append(" FROM secondKillProducts ");
			if(strWhere.Trim()!="")
			{
				strSql.Append(" where "+strWhere);
			}
			strSql.Append(" order by " + filedOrder);
			return DbHelperSQL.Query(strSql.ToString());
		}

		/// <summary>
		/// 获取记录总数
		/// </summary>
		public int GetRecordCount(string strWhere)
		{
			StringBuilder strSql=new StringBuilder();
			strSql.Append("select count(1) FROM secondKillProducts ");
			if(strWhere.Trim()!="")
			{
				strSql.Append(" where "+strWhere);
			}
			object obj = DbHelperSQL.GetSingle(strSql.ToString());
			if (obj == null)
			{
				return 0;
			}
			else
			{
				return Convert.ToInt32(obj);
			}
		}
        /// <summary>
        /// 整张表写入数据库 add by szr
        /// </summary>
        /// <param name="Tname"></param>
        /// <param name="dt"></param>
        /// <param name="exm"></param>
        /// <returns></returns>
        public bool SaveTableData(string Tname, DataTable dt, out string exm)
        {
            using (SqlConnection conn = new SqlConnection(DbHelperSQL.connectionString))
            {
                conn.Open();
                DataTable productsdt = null;

                SqlTransaction transaction = conn.BeginTransaction();
                try
                {
                    SqlCommand command = conn.CreateCommand();
                    command.Connection = conn;
                    command.Transaction = transaction;
                    using (SqlBulkCopy sqlcopy = new SqlBulkCopy(conn, SqlBulkCopyOptions.Default, transaction))
                    {
                        sqlcopy.BulkCopyTimeout = 300;
                        sqlcopy.DestinationTableName = Tname;
                        if (dt != null && dt.Rows.Count > 0)
                        {
                            productsdt = dt.Clone();
                            productsdt.Clear();

                            for (int i = 0; i < dt.Columns.Count; i++)
                            {
                                sqlcopy.ColumnMappings.Add(i, dt.Columns[i].ColumnName);
                            }
                            foreach (DataRow dr in dt.Rows)
                            {
                                command.CommandText = "select count(*) from secondKillProducts where DeleteTime is null and (Down is null or Down=0)  and Pid=" + dr["Pid"].ToString() ;
                                var result = command.ExecuteScalar();
                                if (result == null || result.ToString() == "0")
                                { 
                                    productsdt.Rows.Add(dr.ItemArray);
                                }
                                else 
                                {
                                    //存在则更新   数据的时间点比当前时间小 说明正在抢购中，更新销售进度
                                    if (Convert.ToInt32(dr["InTimeQuantum"]) <= Convert.ToDateTime(DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss")).Hour && dr["UpdateTimeStr"].ToString()==DateTime.Now.ToShortDateString())
                                    {
                                        command.CommandText = "update secondKillProducts set SoldState='" + dr["SoldState"].ToString() + "',UpdateTime='" + DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss") + "',Memo='" + dr["Memo"].ToString() + "',UpdateTimeStr='" + dr["UpdateTimeStr"].ToString() + "' where DeleteTime is null and (Down is null or Down=0)  and Pid=" + dr["Pid"].ToString();
                                        command.ExecuteScalar();
                                    }
                                }
                            }
                        }
                        //处理 取消重复数据
                        if (productsdt != null && productsdt.Rows.Count > 0)
                        {
                            sqlcopy.WriteToServer(productsdt); 
                        }
                        //批量执行数据库操作
                        transaction.Commit();
                    }
                    exm = "";
                    return true;
                }
                catch (Exception ex)
                {
                    exm = ex.Message;
                    conn.Close();
                    return false;
                    // transaction.Rollback(); 
                    // throw ex; 

                }
            }
        }

		/// <summary>
		/// 分页获取数据列表
		/// </summary>
		public DataSet GetListByPage(string strWhere, string orderby, int startIndex, int endIndex)
		{
			StringBuilder strSql=new StringBuilder();
			strSql.Append("SELECT * FROM ( ");
			strSql.Append(" SELECT ROW_NUMBER() OVER (");
			if (!string.IsNullOrEmpty(orderby.Trim()))
			{
				strSql.Append("order by T." + orderby );
			}
			else
			{
				strSql.Append("order by T.PId desc");
			}
			strSql.Append(")AS Row, T.*  from secondKillProducts T ");
			if (!string.IsNullOrEmpty(strWhere.Trim()))
			{
				strSql.Append(" WHERE " + strWhere);
			}
			strSql.Append(" ) TT");
			strSql.AppendFormat(" WHERE TT.Row between {0} and {1}", startIndex, endIndex);
			return DbHelperSQL.Query(strSql.ToString());
		}

		/*
		/// <summary>
		/// 分页获取数据列表
		/// </summary>
		public DataSet GetList(int PageSize,int PageIndex,string strWhere)
		{
			SqlParameter[] parameters = {
					new SqlParameter("@tblName", SqlDbType.VarChar, 255),
					new SqlParameter("@fldName", SqlDbType.VarChar, 255),
					new SqlParameter("@PageSize", SqlDbType.Int),
					new SqlParameter("@PageIndex", SqlDbType.Int),
					new SqlParameter("@IsReCount", SqlDbType.Bit),
					new SqlParameter("@OrderType", SqlDbType.Bit),
					new SqlParameter("@strWhere", SqlDbType.VarChar,1000),
					};
			parameters[0].Value = "secondKillProducts";
			parameters[1].Value = "PId";
			parameters[2].Value = PageSize;
			parameters[3].Value = PageIndex;
			parameters[4].Value = 0;
			parameters[5].Value = 0;
			parameters[6].Value = strWhere;	
			return DbHelperSQL.RunProcedure("UP_GetRecordByPage",parameters,"ds");
		}*/

		#endregion  BasicMethod
		#region  ExtensionMethod

		#endregion  ExtensionMethod
	}
}

